package com.cn.por.auto.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.ds.DSFactory;
import com.cn.por.auto.datasource.dto.DataSourceConfigADTO;
import com.cn.por.auto.datasource.service.DataSourceConfigAService;
import com.cn.por.auto.db.DbUtilCustom;
import com.cn.por.auto.dto.FunctionGena;
import com.cn.por.auto.enums.SqlEnum;
import com.cn.por.util.freemarker.FreeMarkerUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.cn.por.auto.dto.ModelParam;
import com.cn.por.auto.entity.Table;
import com.cn.por.auto.entity.TableDetiles;
import com.cn.por.auto.service.AutoService;
import com.cn.por.util.ZipUtils;
import cn.hsa.base.web.vo.WrapperResponse;

@RestController
@RequestMapping("/web/auto")
@Api(tags="代码生成")
public class AutoController {
	
	@Autowired
	private AutoService autoService;

	@Autowired
	private DbUtilCustom dbUtilCustom;
	@Autowired
	private DataSourceConfigAService dataSourceConfigAService;
	@GetMapping("/getTables")
	@ApiOperation(value = "获取所有表")
	public WrapperResponse<List<Table>> getTables(String dataId){
		DataSourceConfigADTO dataSourceConfigADTO = dataSourceConfigAService.get(dataId);
		List<Table> list = dbUtilCustom.getList(dataSourceConfigADTO, dataSourceConfigADTO.getTableSql(), Table.class, "");
		return WrapperResponse.success(list);
	};
	
	@GetMapping("/getClomun")
	@ApiOperation(value = "获取表字段信息")
	public WrapperResponse<List<TableDetiles>> getTableDetiles(String dataId, String tableName){
		DataSourceConfigADTO dataSourceConfigADTO = dataSourceConfigAService.get(dataId);
		List<TableDetiles> result = dbUtilCustom.getList(dataSourceConfigADTO, dataSourceConfigADTO.getColumnSql(), TableDetiles.class, tableName);
		return WrapperResponse.success(result);
	}
	
	@PostMapping("/autoGrowMan")
	public void autoGrowMan(@RequestBody ModelParam modelParam, HttpServletResponse response) throws IOException {
		Map<String,byte[]>  byteArray = new HashMap<>(autoService.autoGrowMan(modelParam));
		ServletOutputStream outputStream = response.getOutputStream();
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ZipUtils.batchInZip(byteArray, byteArrayOutputStream);
		
		String fileName = URLEncoder.encode("easy.zip", "UTF-8");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		response.setContentType("application/zip");
		byteArrayOutputStream.writeTo(outputStream);
	}
	@PostMapping("/gena")
	@ApiOperation(value = "根据数据库表信息获取基础前后端代码")
	public void gena(@RequestBody ModelParam modelParam, HttpServletResponse response,@RequestParam("dataId") String dataId) throws IOException {

		Map<String,byte[]>  byteArray = new HashMap<>();
		modelParam.getTableConfigDTOS().forEach(item->{
			modelParam.setTableName(item.getTableName());
			DataSourceConfigADTO dataSourceConfigADTO = dataSourceConfigAService.get(dataId);

			List<TableDetiles> result = dbUtilCustom.getList(dataSourceConfigADTO, dataSourceConfigADTO.getColumnSql(), TableDetiles.class, item.getTableName());
			modelParam.setTableColumn(result);
			modelParam.setFrameworkType(dataSourceConfigADTO.getFrameworkType());
			modelParam.setConditionColumn(item.getConditionColumns());
			modelParam.setTableComment(item.getTableComment());
			/**
			 * 找到主键字段
			 */
			result.stream().filter(cols -> "1".equals(cols.getPrimaryCloumn())).forEach(cols -> {
				modelParam.setPrimaryKey(cols.getColumnName());
			});

			byteArray.putAll(autoService.gena(modelParam));
		});

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ZipUtils.batchInZip(byteArray, byteArrayOutputStream);
		String fileName = URLEncoder.encode("easy.zip", "UTF-8");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		response.setContentType("application/zip");
		byteArrayOutputStream.writeTo(response.getOutputStream());
	}

	/**
	 * 生成代码块
	 */
	@PostMapping("/genaBlock")
	@ApiOperation(value = "根据方法名称获取每一层基础代码")
	public String genaCodeBlock(@RequestBody FunctionGena functionGena){
		functionGena.setCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
		return FreeMarkerUtil.dataFormateStr(functionGena,"basic/codeBlock/func.ftl");
	}
}
